﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WebValidation.cs" company="Radical Research Ltd">
//   Copyright (c) Radical Research Ltd. The MIT License (MIT)
// </copyright>
// <summary>
//   
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace RadicalResearch.MiniState.Cookies
{
    using System.Configuration;
    using System.Web.Configuration;

    /// <summary>
    /// Web validation helper object
    /// </summary>
    public class WebValidation
    {
        #region Constants and Fields

        private static readonly object lockObject = new object();

        /// <summary>
        /// bytes used to salt HMAC hashes.
        /// </summary>
        private static byte[] validationKey;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the validation key bytes from the machine config if it is available.
        /// </summary>
        public static byte[] ValidationKey
        {
            get
            {
                if (validationKey == null)
                {
                    lock (lockObject)
                    {
                        if (validationKey == null)
                        {
                            validationKey = GetMachineKey();
                        }
                    }
                }

                if (validationKey == null)
                {
                    validationKey = Validation.ValidationKey;
                }

                return validationKey;
            }
        }

        private static byte[] GetMachineKey()
        {
            // Get validation key from web config.
            MachineKeySection machineKeySection = (MachineKeySection)ConfigurationManager.GetSection("system.web/machineKey");
            if (null != machineKeySection)
            {
                if (!machineKeySection.ValidationKey.Contains("AutoGenerate"))
                {
                    return Validation.HexStringToByteArray(machineKeySection.ValidationKey);
                }
            }

            return null;
        }

        #endregion
    }
}
